/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sinemaproject;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import entity.Salon;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;


/**
 *
 * @author Nurullah YILMAZ
 */
public class SalonYonet extends javax.swing.JFrame {

    public static void main(String args[]) {
        SalonYonet salonYonet = new SalonYonet();
        salonYonet.setVisible(true);
    }
    
    /** Creates new form SalonYonet */
    public SalonYonet() {
        this.setTitle("Salon Yönetimi");
        initComponents();
        refreshSalonUITable();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();
        jTextField2 = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setName("Form"); // NOI18N

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        jPanel1.setName("jPanel1"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(sinemaproject.SinemaProjectApp.class).getContext().getResourceMap(SalonYonet.class);
        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton1MouseClicked(evt);
            }
        });
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jTextField1.setText(resourceMap.getString("jTextField1.text")); // NOI18N
        jTextField1.setName("jTextField1"); // NOI18N

        jTextField2.setText(resourceMap.getString("jTextField2.text")); // NOI18N
        jTextField2.setName("jTextField2"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null}
            },
            new String [] {
                "Id", "Salon Adı", "Kapasite"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            @Override
            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            @Override
            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.setName("jTable1"); // NOI18N
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jButton2.setText(resourceMap.getString("jButton2.text")); // NOI18N
        jButton2.setEnabled(false);
        jButton2.setName("jButton2"); // NOI18N
        jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton2MouseClicked(evt);
            }
        });

        jButton3.setText(resourceMap.getString("jButton3.text")); // NOI18N
        jButton3.setEnabled(false);
        jButton3.setName("jButton3"); // NOI18N
        jButton3.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton3MouseClicked(evt);
            }
        });

        jSeparator1.setName("jSeparator1"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 603, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jTextField2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 76, Short.MAX_VALUE)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 603, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 157, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jTextField2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>                        

    private EntityManagerFactory emf;
    private DefaultTableModel tmodel;
    
    
    private EntityManager getEntityManager() {
        if (emf == null) {
            emf = Persistence.createEntityManagerFactory("SinemaProjectPU");
        }
        return emf.createEntityManager();
    }
    
    //Film Tip Ekle
    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {                                      
        // TODO add your handling code here:
        int temp=0;
        if(getSalonByName(jTextField1.getText())!=null)
            JOptionPane.showMessageDialog(null, "Boyle bir kayıt zaten var!","UYARI",JOptionPane.WARNING_MESSAGE);
        else if(jTextField1.getText().isEmpty()|| jTextField2.getText().isEmpty())
            JOptionPane.showMessageDialog(null, "Doldurulması zorunlu alanları boş bırakmayın!","UYARI",JOptionPane.WARNING_MESSAGE);
        else { 
            try {
                temp = Integer.parseInt(jTextField2.getText());
            } catch(Exception e) {
                JOptionPane.showMessageDialog(null, "Hatalı değer girdiniz!","UYARI",JOptionPane.WARNING_MESSAGE);
                return;
            }
            
            Salon yeniSalon = new Salon();
            yeniSalon.setSalonAdi(jTextField1.getText());
            yeniSalon.setKapasite(temp);
            addSalon(yeniSalon);
            refreshSalonUITable();
        }
    }                                     
    
    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {                                     
        // TODO add your handling code here:
        int row = jTable1.getSelectedRow();        
        
        //Kutuyu güncelle
        jTextField1.setText((String)jTable1.getValueAt(row, 1));
        jTextField2.setText((String)jTable1.getValueAt(row, 2));
        
        //
        jButton2.setEnabled(true);
        jButton3.setEnabled(true);
    }          
    
    

    //Film Tip Güncelle    
    private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {                                      
        // TODO add your handling code here:
        int row = jTable1.getSelectedRow();
        if(row==-1)//eleman secilmezse
            return;
        
        int temp=0;
        
        if(getSalonByName(jTextField1.getText())!=null && !(jTable1.getValueAt(row, 1).toString().equals(jTextField1.getText())))
            JOptionPane.showMessageDialog(null, "Boyle bir kayıt zaten var!","UYARI",JOptionPane.WARNING_MESSAGE);
        else if(jTextField1.getText().isEmpty() || jTextField2.getText().isEmpty())
            JOptionPane.showMessageDialog(null, "Doldurulması zorunlu alanları boş bırakmayın!","UYARI",JOptionPane.WARNING_MESSAGE);
        else {
            try {
                temp = Integer.parseInt(jTextField2.getText());
            } catch(Exception e) {
                JOptionPane.showMessageDialog(null, "Hatalı değer girdiniz!","UYARI",JOptionPane.WARNING_MESSAGE);
                return;
            }
            Salon salon = new Salon();
            salon.setIdSalon( (Integer)jTable1.getValueAt(row, 0));
            salon.setSalonAdi(jTextField1.getText());
            salon.setKapasite(temp);
            updateSalon(salon);
            refreshSalonUITable();

            jButton2.setEnabled(false);
            jButton3.setEnabled(false);
        }
    }                                     

    //Film Tip Sil    
    private void jButton3MouseClicked(java.awt.event.MouseEvent evt) {                                      
        // TODO add your handling code here:
        int row = jTable1.getSelectedRow();
        if(row==-1)//eleman secilmezse
            return;
        Salon salon = new Salon();
        salon.setIdSalon( (Integer)jTable1.getValueAt(row, 0));
        
        removeSalon(salon);
        refreshSalonUITable();
        
        jButton2.setEnabled(false);
        jButton3.setEnabled(false);         
    }                                     

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
    }                                        

    public boolean addSalon(Salon salon) {
      EntityManager em = getEntityManager();
       try{
         em.getTransaction().begin();
         em.persist(salon); 
         em.getTransaction().commit();
       } finally {
        em.close();
        return false;
       }
    }    
    
    public boolean removeSalon(Salon salon) {
      EntityManager em = getEntityManager();
      try{
        em.getTransaction().begin();
        Salon tipx = em.find(Salon.class, salon.getIdSalon());
        em.remove(tipx);
        em.getTransaction().commit();
      } finally {
        em.close();
        return false;
      }
    }
    
    public boolean updateSalon(Salon salon) {
      EntityManager em = getEntityManager();
      try{
        em.getTransaction().begin();
        Salon tipx = em.find(Salon.class, salon.getIdSalon());
        tipx.setSalonAdi(salon.getSalonAdi());
        tipx.setKapasite(salon.getKapasite());
        em.getTransaction().commit();
      } finally {
        em.close();
        return false;
      }
    }    
    
    public List<Salon> getAllSalon(){        
        List<Salon> tips;        
        EntityManager em = getEntityManager();
        try{
            em.getTransaction().begin();
            tips = em.createNamedQuery("Salon.findAll").getResultList();
        } finally {
            em.close();
        }                
        return tips;        
    }
    
    
    public Salon getSalonByName(String str){        
        Salon salon;
        
        EntityManager em = getEntityManager();
        try{
            em.getTransaction().begin();
            salon = (Salon) em.createNamedQuery("Salon.findBySalonAdi").setParameter("salonAdi", str).getSingleResult();
        }catch(Exception ex){
            return null;  
        }finally {
            em.close();
        }                
        return salon;        
    }    
    
    public void refreshSalonUITable(){
        
        List<Salon> tips;
        tips = getAllSalon();
        
        tmodel = (DefaultTableModel) jTable1.getModel();
        //clean tmodel...
        tmodel.setRowCount(0);
        
        
        for(Salon salon : tips){
            //System.out.println(tip.getTipIsmi());
            tmodel.addRow(new Object[]{salon.getIdSalon(), salon.getSalonAdi(), Integer.toString(salon.getKapasite())});
        }

        jTable1.setModel(tmodel);
    }          
    
    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration                   
}
